package com.klaus.ohMySpace.service.Impl;

import com.klaus.ohMySpace.conf.Configurator;
import com.klaus.ohMySpace.dao.TokenDao;
import com.klaus.ohMySpace.entity.Token;
import com.klaus.ohMySpace.service.TokenService;
import com.klaus.ohMySpace.util.JsonUtil;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * Created by Mklaus on 15/8/11.
 */
@Service
public class TokenServiceImpl implements TokenService{
    @Resource
    private TokenDao tokenDao;

    @Override
    public String saveOrUpdate(int userId, String deviceId) {
        Token token;
        List<Token> tokens;

        UUID uuid = UUID.randomUUID();
        String t = (uuid.toString()).replace("-","");

        DetachedCriteria dc = DetachedCriteria.forClass(Token.class);
        dc.add(Restrictions.eq("userId",userId));

        if ((tokens = tokenDao.search(dc)).size() > 0){
            token = tokens.get(0);
            token.setToken(t);
            token.setDeviceId(deviceId);
            tokenDao.update(token);
        }else {
            token = new Token(userId,t,deviceId);
            tokenDao.save(token);
        }

        return t;
    }

    @Override
    public boolean isPass(String t, String deviceId) {

        Long timeInterval = Configurator.getInstance().getLong("token.expireTimeInterval");

        Token token;
        List<Token> tokenList;

        DetachedCriteria dc = DetachedCriteria.forClass(Token.class);
        dc.add(Restrictions.eq("token",t)).add(Restrictions.eq("deviceId",deviceId));

        if ((tokenList = tokenDao.search(dc)).size() > 0){
            token = tokenList.get(0);
            if ((System.currentTimeMillis() - token.getModify_time()) > timeInterval) {
                return false;
            }else {
                tokenDao.update(token);
                return true;
            }
        }

        return false;
    }
}
